package org.bluweb.g4wicket.webfont;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.wicket.markup.html.IHeaderResponse;
import org.bluweb.g4wicket.G4WicketBehaviour;


@SuppressWarnings("serial")
public class WebFontLoader extends G4WicketBehaviour {

	//TODO support multiple providers
	
	public static enum Style { NORMAL, ITALIC };
	public static enum Weight { ULTRALIGHT, LIGHT, NORMAL, BOLD };
	
	private final List<String> families = new ArrayList<String>();
	
	public WebFontLoader(String id) {
		super(id);
	}
	
	public void load( String fontName ) {
		this.load( fontName, Style.NORMAL, Weight.NORMAL );
	}
	
	public void load( String fontName, Style style ) {
		this.load( fontName, style, Weight.NORMAL );
	}
	
	public void load( String fontName, Style style, Weight weight ) {

		if( style == null ) {
			style = Style.NORMAL;
		}
		if( weight == null ) {
			weight = Weight.NORMAL;
		}
		
		StringBuilder builder = new StringBuilder( fontName );
		builder.append( ':' );
		builder.append( this.getStyleIdentifier( style ) );
		builder.append( this.getWeightIdentifier( weight ) );
		fontName = builder.toString();

		this.families.add( fontName );
	}
	
	private String getStyleIdentifier( Style style) {
		
		if( style != null ) {
			switch( style ) {
				case NORMAL: return "b";
				case ITALIC: return "i";
			}
		}
		return null;
	}

	private String getWeightIdentifier( Weight weight ) {
		
		if( weight != null ) {
			switch( weight ) {
				case ULTRALIGHT: return "2";
				case LIGHT: return "3";
				case NORMAL: return "4";
				case BOLD: return "7";
			}
		}
		return null;
	}
	
	
	@Override
	public void renderHead(IHeaderResponse response) {
		super.renderHead(response);
		
		Map<String,Object> parameters = new HashMap<String,Object>();
		parameters.put( "id", this.getId() );

		StringBuilder builder = new StringBuilder();
		for( String familie : families ) {
			if( builder.length() > 0 ) {
				builder.append( ',' );
			}
			builder.append( "'" ).append( familie ).append( "'" );
		}
		
		parameters.put( "families", builder.toString() );
		
		String javascript = this.getJavaScript( "WebFontLoader.js", parameters );
		response.renderJavascript( javascript, this.getId() );
	}
}
